import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Card, Form, Empty, Icon, Tooltip, Table, Spin, Collapse } from 'antd';
import { useUpdateEffect } from '@umijs/hooks';
import classNames from 'classnames';
import ScrollBar from '@/components/ScrollBar';
import request from '@/utils/request';
import styles from '@/pages/FlowComp/less/stepList.less';

function ObjFlowView(props) {
  const [flowNodeList, setFlowNodeList] = useState([]);
  const [planData, setPlanData] = useState([]);
  const [tableList, setTableList] = useState([]);
  const [loading, setLoading] = useState(false);

  // 初始化
  useEffect(() => {
    if (props.objInstId != null) {
      request('pmc/pms/PmOrderFlowNodeController/queryListWithExec', {
        data: { objInstId: props.objInstId, objType: props.objType },
      }).then(res => {
        if (res && res.success) {
          setFlowNodeList(res.data);
        }
      });
    }
  }, [props.objInstId]);

  useUpdateEffect(() => {
    if (planData != null) {
      const tableList = [];
      planData.map(plan => {
        const table = (
          <div style={{ marginBottom: 20 }}>
            <div>
              <h4 style={{ display: 'inline' }}>方案名称：</h4>
              <span>{plan.planName}</span>
              &nbsp; &nbsp; &nbsp;
              <h4 style={{ display: 'inline' }}>事件名称：</h4>
              <span>{plan.eventName}</span>
            </div>
            <Table
              rowKey={record => record.ruleId}
              columns={columns}
              pagination={false}
              dataSource={plan.ruleExecList}
              bordered
            />
          </div>
        );
        tableList.push(table);
      });
      setTableList(tableList);
    } else {
      setTableList([]);
    }
  }, [planData]);

  const queryPlanData = item => {
    request('pmc/pms/PmOrderWorkController/flowExec/getRuleLog', {
      data: { execId: item.execId },
    }).then(res => {
      if (res && res.success) {
        if (res.data) {
          // eslint-disable-next-line array-callback-return
          res.data.map(item => {
            if (item.ruleExecList) {
              // eslint-disable-next-line array-callback-return
              item.ruleExecList.map(exec => {
                exec.children = exec.exeList;
              });
            }
          });
        }
        setPlanData(res.data);
      }
    });
  };

  const onChange = item => {
    queryPlanData(item);
  };

  const retryRulePlan = record => {
    // 找父节点数据
    const { planCode, objId, objType } = planData.filter(item => {
      return (
        item.ruleExecList !== null &&
        item.ruleExecList.filter(t => {
          return t.ruleId === record.ruleId && t.execResult === record.execResult;
        }).length > 0
      );
    })[0];

    setLoading(true);
    request('pmc/pms/rulePlan/retryRulePlan', {
      data: {
        planCode,
        objId,
        objType,
      },
    }).then(res => {
      setLoading(false);
      if (res && res.success) {
        setPlanData([...planData]);
      }
    });
  };

  const getStatusStyle = item => {
    if (item.execStatusCd === '1200') {
      return styles.finish;
    }
    if (item.execStatusCd === '1000') {
      return styles.process;
    }
    if (item.execStatusCd === '1100') {
      return styles.error;
    }
    return null;
  };

  const getIcon = (item, index) => {
    if (item.execStatusCd === '1200') {
      return <Icon type="check" />;
    }
    if (item.execStatusCd === '1100') {
      return <Icon type="close" />;
    }
    return <span className={styles.stepsNumber}>{index + 1}</span>;
  };

  const getTitle = item => {
    if (item.execStatusCd === '1200') {
      return <span style={{ color: 'rgba(0, 0, 0, 0.65)' }}>{item.flowNodeName}</span>;
    }
    if (item.execStatusCd === '1000') {
      return <span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>{item.flowNodeName}</span>;
    }
    if (item.execStatusCd === '1100') {
      return <span style={{ color: 'rgba(245, 34, 45, 0.85)' }}>{item.flowNodeName}</span>;
    }
    return <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>{item.flowNodeName}</span>;
  };

  const columns = [
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      render: (text, record) => {
        return record.ruleRelName !== null ? `[${record.ruleRelName}]${text}` : text;
      },
    },
    {
      title: '规则编码',
      dataIndex: 'ruleCode',
    },
    {
      title: '状态',
      dataIndex: 'execResult',
      render: text => {
        return text === '-1' ? '未处理' : '已处理';
      },
    },
    {
      title: '处理结果',
      dataIndex: 'execResultName',
    },
    {
      title: '执行时间',
      dataIndex: 'execDate',
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      render: (text, record) => {
        return (
          <span style={{ display: record.execResult === '1' ? 'bolck' : 'none' }}>
            <a
              onClick={() => {
                retryRulePlan(record);
              }}
            >
              单步执行
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <Spin spinning={loading} tip="处理中，请稍候。。。">
      <Collapse
        className="cute"
        defaultActiveKey={['1']}
        bordered={false}
        expandIconPosition="right"
      >
        <Collapse.Panel header="流程导向" key="1">
          <div className={classNames(styles.steps)} style={{ textAlign: 'left', marginBottom: 30 }}>
            <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 8 }}>
              <div className={classNames(styles.stepsItemIconSmall, [styles.finish])}>
                <Icon type="check" />
              </div>
              <div className={styles.stepsItemContentSmall}>
                <Tooltip placement="topLeft" title="处理完成">
                  <span style={{ color: 'rgba(0, 0, 0, 0.65)' }}>处理完成</span>
                </Tooltip>
              </div>
            </div>
            <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 8 }}>
              <div className={classNames(styles.stepsItemIconSmall, [styles.process])}>2</div>
              <div className={styles.stepsItemContentSmall}>
                <Tooltip placement="topLeft" title="处理完成">
                  <span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>正在处理</span>
                </Tooltip>
              </div>
            </div>
            <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 8 }}>
              <div className={classNames(styles.stepsItemIconSmall, [styles.error])}>
                <Icon type="close" />
              </div>
              <div className={styles.stepsItemContentSmall}>
                <Tooltip placement="topLeft" title="处理完成">
                  <span style={{ color: 'rgba(245, 34, 45, 0.85)' }}>处理异常</span>
                </Tooltip>
              </div>
            </div>
            <div className={styles.stepsItem} style={{ minWidth: 0, marginRight: 8 }}>
              <div className={classNames(styles.stepsItemIconSmall)}>4</div>
              <div className={styles.stepsItemContentSmall}>
                <Tooltip placement="topLeft" title="处理完成">
                  <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>未处理</span>
                </Tooltip>
              </div>
            </div>
          </div>

          {flowNodeList.length > 0 ? (
            <ScrollBar autoHide autoHeight autoHeightMin="56px">
              <div className={classNames(styles.steps)}>
                {flowNodeList.map((item, index) => (
                  <div className={styles.stepsItem}>
                    <div
                      className={classNames(styles.stepsItemIcon, [getStatusStyle(item)])}
                      onClick={() => onChange(item)}
                    >
                      {getIcon(item, index)}
                    </div>
                    <div className={styles.stepsItemContent} onClick={() => onChange(item)}>
                      <Tooltip placement="topLeft" title={item.flowNodeName}>
                        {getTitle(item)}
                      </Tooltip>
                    </div>
                    <div
                      className={classNames(styles.stepsItemLine, [
                        item.execStatusCd > '1000' ? styles.lineFish : null,
                      ])}
                    />
                  </div>
                ))}
              </div>
            </ScrollBar>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无流程数据" />
          )}

          <h4 className="margin-z-lg">规则执行情况</h4>

          {/* <Divider className="small" /> */}

          {tableList.length ? (
            tableList.map(item => {
              return item;
            })
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          )}
        </Collapse.Panel>
      </Collapse>
    </Spin>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(ObjFlowView));
